package com.nf.dao.impl;

import com.nf.dao.CommentInfoDao;
import com.nf.entity.CommentInfo;
import com.nf.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CommentInfoDaoImpl implements CommentInfoDao {
    @Override
    public int add(CommentInfo comment) {
        int r=0;

        Connection conn= DBUtil.getConnection();
        String sql="insert into commentInfo values(?,?,?,?,default,?,?)";
        PreparedStatement pstmt=null;
        try {
            pstmt=conn.prepareStatement(sql);
            pstmt.setString(1, comment.getUserName());
            pstmt.setString(2, comment.getImage());
            pstmt.setString(3, comment.getFilmName());
            pstmt.setString(4, comment.getContent());
            pstmt.setInt(5,comment.getFilmId());
            pstmt.setInt(6,comment.getUserId());
            r= pstmt.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.close(null,pstmt,conn);
        }
        return r;
    }

    @Override
    public List<CommentInfo> selectById(int filmId) {
        List<CommentInfo> list=new ArrayList<>();

        Connection conn=DBUtil.getConnection();
        String sql="select * from commentInfo where film_id=? order by comment_id desc";
        PreparedStatement pstmt=null;
        ResultSet rst=null;
        try {
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1,filmId);
            rst= pstmt.executeQuery();
            while (rst.next()){
                int commentId=rst.getInt(1);
                String userName=rst.getString(2);
                String image=rst.getString(3);
                String filmName=rst.getString(4);
                String content=rst.getString(5);
                String commentTime=rst.getString(6);
                int userId=rst.getInt(8);

                CommentInfo comment=new CommentInfo(commentId,userName,image,filmName,content,commentTime,filmId,userId);
                list.add(comment);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.close(rst,pstmt,conn);
        }

        return list;
    }
}
